package cn.wolfcode.luowowo.website.web.controller;

import cn.wolfcode.luowowo.article.domain.Destination;
import cn.wolfcode.luowowo.article.domain.Question;
import cn.wolfcode.luowowo.article.domain.Travel;
import cn.wolfcode.luowowo.article.query.QuestionQuery;
import cn.wolfcode.luowowo.article.service.IDestinationService;
import cn.wolfcode.luowowo.article.service.IQuestionService;
import cn.wolfcode.luowowo.cache.service.IQuestionStatisService;
import cn.wolfcode.luowowo.cache.service.IUserInfoRedisService;
import cn.wolfcode.luowowo.cache.service.IUserStatisService;
import cn.wolfcode.luowowo.cache.vo.QuestionStatisVO;
import cn.wolfcode.luowowo.cache.vo.StrategyStatisVO;
import cn.wolfcode.luowowo.cache.vo.UserStatisVo;
import cn.wolfcode.luowowo.comment.domain.AskComment;
import cn.wolfcode.luowowo.comment.query.AskCommentQuery;
import cn.wolfcode.luowowo.comment.service.IAskCommentService;
import cn.wolfcode.luowowo.common.util.AjaxResult;
import cn.wolfcode.luowowo.member.domain.UserInfo;
import cn.wolfcode.luowowo.website.annotation.UserParam;
import cn.wolfcode.luowowo.website.util.CookieUtil;
import cn.wolfcode.luowowo.website.util.UMEditorUploader;
import com.alibaba.dubbo.config.annotation.Reference;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

@Controller
@RequestMapping("/question")
public class QuestionController {

    @Reference
    private IQuestionService questionService;

    @Reference
    private IDestinationService destinationService;

    @Reference
    private IQuestionStatisService questionStatisService;

    @Reference
    private IUserInfoRedisService userInfoRedisService;

    @Reference
    private IAskCommentService askCommentService;

    @Reference
    private IUserStatisService userStatisService;

    @RequestMapping("")
    public String list(Model model, @ModelAttribute("qo")QuestionQuery qo){
        PageInfo pageInfo = questionService.query(qo);
        model.addAttribute("pageInfo", pageInfo);
            //用户评论数前十
        List<UserStatisVo> userStatisVos = userStatisService.queryTop10();
        if(userStatisVos.size()>=1){
            model.addAttribute("utop1",userStatisVos.remove(0));
        }
        if(userStatisVos.size()>=1){
            model.addAttribute("utop2",userStatisVos.remove(0));
        }
        if(userStatisVos.size()>=1){
            model.addAttribute("utop3",userStatisVos.remove(0));
        }
        model.addAttribute("usvs",userStatisVos);
        return "wenda/wenda";
    }

    @RequestMapping("/input")
    public String input(Model model){
        List<Destination> dests = destinationService.getDestsByDeep(3);
        model.addAttribute("dests",dests);
        return "wenda/public";
    }

    @RequestMapping("/saveOrUpdate")
    @ResponseBody
    public Object saveOrUpdate(@UserParam UserInfo user, Question question){
        //获取当前用户Id  1.页面传当前登录用户信息 2.从Cookie中获取token然后去redis拿
        if(user == null){
            return AjaxResult.FAIL;
        }
        question.setUser(user);
        Long id = questionService.saveOrUpdate(question);
        return AjaxResult.SUCCESS.addData(id);
    }

    @RequestMapping("/detail")
    public String detail(Model model, Long id, @UserParam UserInfo userInfo){
        Question question = questionService.get(id);
        model.addAttribute("question", question);
        questionStatisService.increaseViewNum(id, 1);
        QuestionStatisVO vo = questionStatisService.getQuestionStatisVo(id);
        model.addAttribute("vo", vo);
        model.addAttribute("user", userInfo);
        AskComment askComment = askCommentService.getThumbupnum(id);
        model.addAttribute("ask", askComment);
        return "wenda/wendaDetail";
    }

    @RequestMapping("/commentThumbUp")
    @ResponseBody
    public Object commentThumbUp(String toid,Long fromid){
        askCommentService.commentThumbUp(toid,fromid);
        return AjaxResult.SUCCESS;
    }

    @RequestMapping("/commentAdd")
    @ResponseBody
    public Object commentAdd(AskComment comment, @UserParam UserInfo userInfo){
        comment.setUserId(userInfo.getId());
        comment.setHeadImgUrl(userInfo.getHeadImgUrl());
        comment.setLevel(userInfo.getLevel());
        comment.setUsername(userInfo.getNickname());
        askCommentService.saveOrUpdate(comment);

        //评论数
        questionStatisService.increaseReplyNum(comment.getQuestionId(),1);
        QuestionStatisVO vo = questionStatisService.getQuestionStatisVo(comment.getQuestionId());

        UserStatisVo userStatisVo = new UserStatisVo();
        userStatisVo.setUserId(userInfo.getId());
        userStatisVo.setHeadImgUrl(userInfo.getHeadImgUrl());
        userStatisVo.setNickname(userInfo.getNickname());
        userStatisVo.setLevel(userInfo.getLevel());
        //用户统计对象是否存在，否的话创建 key 前缀+userId
        userStatisService.setUserStatisVo(userStatisVo);
        // TODO: 2020/4/5 回答一次，这个用户的回答数加+1
        userStatisService.addScore(userInfo.getId(),1);
        return AjaxResult.SUCCESS.addData(vo.getAsknum());
    }

    @RequestMapping("/comment")
    public String comment(Model model, Long questionid, @UserParam UserInfo userInfo, @ModelAttribute("qo")AskCommentQuery qo){
        Question question = questionService.get(questionid);
        model.addAttribute("question", question);
        QuestionStatisVO vo = questionStatisService.getQuestionStatisVo(questionid);
        model.addAttribute("vo", vo);
        model.addAttribute("user", userInfo);
        qo.setQuestionId(questionid);
        model.addAttribute("page",askCommentService.query(qo));
        return "wenda/wendaDetail";
    }

    @RequestMapping("/addThumpnum")
    @ResponseBody
    public Object questionThumbup(Long qid, @UserParam UserInfo userInfo){
        if(userInfo == null){
            AjaxResult result = new AjaxResult(false, "请先登录");
            result.setCode(102);
            return result;
        }
        boolean ret = questionStatisService.questionThumbup(qid, userInfo.getId());
        return new AjaxResult(ret, "").addData(questionStatisService.hasQuestionStatisVO(qid));
    }

    @Value(("${file.path}"))
    private String filePath;
    //上传图片
    @RequestMapping("/contentImage")
    @ResponseBody
    public String uploadUEImage(MultipartFile upfile, HttpServletRequest request) throws Exception{
        UMEditorUploader up = new UMEditorUploader(request);
        String[] fileType = {".gif" , ".png" , ".jpg" , ".jpeg" , ".bmp"};
        up.setAllowFiles(fileType);
        up.setMaxSize(10000); //单位KB
        up.upload(upfile, filePath);

        String callback = request.getParameter("callback");
        String result = "{\"name\":\""+ up.getFileName() +"\", \"originalName\": \""+ up.getOriginalName() +"\", \"size\": "+ up.getSize()
                +", \"state\": \""+ up.getState() +"\", \"type\": \""+ up.getType() +"\", \"url\": \""+ up.getUrl() +"\"}";
        result = result.replaceAll( "\\\\", "\\\\" );
        if(callback == null ){
            return result ;
        }else{
            return "<script>"+ callback +"(" + result + ")</script>";
        }
    }
}
